package com.prothink.threadadmindemo.interceptor;

import com.prothink.threadadmindemo.util.JWTTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author mayanping
 * @title: JWTTokenInterceptor
 * @projectName ThreadAdminDemo
 * @description: TODO
 * @date 2024/9/1614:11
 */
public class JWTTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("request method:" + request.getMethod() + ", url: " + request.getRequestURI());

        if(request.getMethod().equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader("Authorization");
        System.out.println("Token: " + token);

        //1. 判断有没有Token，拒绝用户访问
        if(StringUtils.isEmpty(token)){
            response.setStatus(401);
            return false;
        }

        //2. 解析Token，如果解析报错， 也说明Token有问题
        token = token.replace("Bearer ", "");
        String subject = "";
        try{
            subject = JWTTokenUtil.parseToken(token);
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }

        //3. 数据库查询这个账号，看存不存在这个用户，如果存在就说明正常的Token， 如果不存在 就说明这个Token有问题
        System.out.println("subject: " + subject);

        return true;
    }
}
